import json
from decimal import Decimal
from pickle import FALSE
from django.shortcuts import render
from jedi.inference.value import instance
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
import uuid
import sku
from .serializer import OrderSerializer,OrderInfoSerializer,physicalDistributionHistorySerializer
from order.models import Order,physical_distribution_history
from sku.serializer import SkuSerializer
from rest_framework.decorators import action
from buyHigh.utils.buyHighResponse import APIResponse
from .paginations import PageNumberPagination
# Create your views here.
class OrderView(GenericViewSet):
    permission_classes = [IsAuthenticated]
    authentication_classes = [JSONWebTokenAuthentication]
    pagination_class = PageNumberPagination
    queryset = Order.objects.all()
    serializer_class = OrderSerializer
    @action(detail=False, methods=['post'])
    def create_order(self, request,*args,**kwargs):
        print("进入订单模块")
        print(request.data)
        user=request.user
        data = request.data
        order_number=self.__get_order_nuber()
        if len(data)>1:
            # 如果有多个商品一起提交，把第一个作为订单
            ser=self.get_serializer(data=data[0],context={"user":user,'order_number':order_number})
            if ser.is_valid():
                order_obj=ser.save()
                # 把其他商品作为子订单
                for item in data[1:]:
                    item['parent_order']=order_obj.id
                son_ser=self.get_serializer(data=data[1:],many=True,context={"user":user,'order_number':order_number})
                if son_ser.is_valid():
                    son_ser.save()
                    return APIResponse(statusCode=200,message="订单创建成功",code=200,data=son_ser.data)
                else:
                    return APIResponse(statusCode=400,message=son_ser.errors,code=400)
            else:
                return APIResponse(statusCode=400,message=ser.errors,code=400)
        else:
            ser=self.get_serializer(data=data[0],context={"user":user,'order_number':order_number})
            print('创建一个订单')
            if ser.is_valid():
                print("数据合法")
                ser.save()
                return APIResponse(statusCode=200,message="订单创建成功",code=200,data=ser.data)
            else:
                print(ser.errors)
                return APIResponse(statusCode=400,message=ser.errors,code=400)
    @action(detail=False, methods=['get'])
    def get_orders_by_id(self, request,*args,**kwargs):
        user=request.user
        # 设计的数据库，order和product是一对多的关系，
        # 如果用户同时购买了多个商品，使用同一个订单号，
        # 但是创建出多个订单，这样方便管理复杂的订单
        order_number=request.GET['order_number']
        ordersQuerySet=Order.objects.filter(order_number=order_number,user=user)
        ser=OrderInfoSerializer(ordersQuerySet,many=True)
        if not ser.data:
            return APIResponse(statusCode=400,message="订单不存在",code=400)
        return APIResponse(statusCode=200,data=ser.data,code=200)
    # 生成订单号
    def __get_order_nuber(self):
        # 方案 1：时间戳 + 随机数
        from datetime import datetime
        import random
        return f"{datetime.now().strftime('%Y%m%d%H%M%S')}{random.randint(1000,9999)}"
    @action(detail=False, methods=['get'])
    def get_all_orders(self, request,*args,**kwargs):
        user=self.request.user
        try:
            pages=request.GET['pages']
        except:
            pages=1
        order_type=request.GET['type']
        print(order_type)
        if order_type=='0': #     全部订单
            orders=Order.objects.filter(user=user,parent_order=None).order_by('-created_time')
        elif order_type=='1': #     待付款
            orders=Order.objects.filter(user=user,order_of_payment=1,parent_order=None).order_by('-created_time')
        elif order_type=='2': #     代发货
            orders=Order.objects.filter(user=user,order_of_payment=2,parent_order=None).order_by('-created_time')
        elif order_type=='3': #     待收货
            orders=Order.objects.filter(user=user,order_of_payment=3,parent_order=None).order_by('-created_time')
        elif order_type=='4': #     待评价
            orders=Order.objects.filter(user=user,order_of_payment=4,parent_order=None).order_by('-created_time')
        else:
            return APIResponse(statusCode=400, message="参数未携带", code=400)
        if not orders:
            return APIResponse(statusCode=400,message="暂无订单",code=400,data='')
        # 修改分页后的数据处理
        paginated_orders = self.paginate_queryset(queryset=orders)
        ser=OrderInfoSerializer(paginated_orders,many=True)
        return self.get_paginated_response(ser.data)
    @action(detail=False, methods=['delete'])
    def delete_order(self, request,*args,**kwargs):
        order_number=request.GET['order_number']
        orderQuerySet=Order.objects.filter(order_number=order_number,user=request.user)
        if not orderQuerySet:
            return APIResponse(statusCode=400,message="订单不存在",code=400)
        orderQuerySet.delete()
        return APIResponse(statusCode=200,message="删除成功",code=200)
    @action(detail=False, methods=['put'])
    def update_order(self, request,*args,**kwargs):
        import random
        random_numbers=''
        for i in range(10):
            random_numbers+=str(random.randint(0,9))
        order_number=request.GET['order_number']
        orderQuerySet=Order.objects.filter(order_number=order_number,user=request.user)
        if not orderQuerySet:
            return APIResponse(statusCode=400,message="订单不存在",code=400)
        # 为实现测试，假支付功能
        orderQuerySet.update(pay_time=datetime.now(),transaction_id=random_numbers,order_of_payment=2)
        return APIResponse(statusCode=200,message="支付成功",code=200)
    #
    @action(detail=False, methods=['delete'])
    def cancel_order(self, request,*args,**kwargs):
        order_number=request.GET['order_number']
        orderQuerySet=Order.objects.filter(order_number=order_number,user=request.user)
        if not orderQuerySet:
            return APIResponse(statusCode=400,message="订单不存在",code=400)
        for order in orderQuerySet:
            if order.order_of_payment!=1:
                return APIResponse(statusCode=400,message="订单状态不正确",code=400)
            order.sku.frozen_stock-=order.num
            order.save()
        orderQuerySet.delete()
        return APIResponse(statusCode=200,message="取消成功",code=200)
    @action(detail=False, methods=['put'])
    def confirm_receipt(self,request,*args,**kwargs):
        order_number=request.data['order_number']
        orderQuerySet=Order.objects.filter(order_number=order_number,user=request.user,order_of_payment=3)
        print('orderQuerySet',orderQuerySet)
        if not orderQuerySet:
            return APIResponse(statusCode=400,message="订单不存在",code=400)
        for order in orderQuerySet:
            if order.order_of_payment!=3:
                return APIResponse(statusCode=400,message="订单状态不正确",code=400)
            #
            user=request.user
            # 直系上级有2%的提成
            # 不可叠加
            if user.superiors:
                print('superiors')
                print(user.superiors)
                user.superiors.balance += Decimal(str(order.actual_payment)) * Decimal('0.02')
                user.superiors.save()
                # 隔代1%
                if user.superiors.superiors:
                    user.superiors.superiors.balance=(user.superiors.superiors.balance*100+order.actual_payment*100*1)/100
                    user.superiors.superiors.save()
                    # 隔两代0.5%
                    if user.superiors.superiors.superiors:
                        user.superiors.superiors.superiors.balance=(user.superiors.superiors.superiors.balance*100+order.actual_payment*100*5)/1000
                        user.superiors.superiors.superiors.save()
                        # 不论任何人下单，董事级都有%0.2
                        if user.superiors.superiors.superiors.superiors:
                            user.superiors.superiors.superiors.superiors.balance=(user.superiors.superiors.superiors.superiors.balance*100+(order.actual_payment*100*2))/1000
                            user.superiors.superiors.superiors.superiors.save()
            order.order_of_payment=4
            order.save()
        return APIResponse(statusCode=200,message="确认收货成功",code=200)
class physicalDistributionHistoryView(GenericViewSet):
    permission_classes = [IsAuthenticated]
    authentication_classes = [JSONWebTokenAuthentication]
    queryset = physical_distribution_history.objects.all()
    serializer_class = OrderSerializer
    @action(detail=False, methods=['GET'])
    def get_phy_buy_order_number(self,request,*args,**kwargs):
        order_number=request.GET['order_number']
        # 存储查询到的所有物流信息
        phy_info=[]
        order_query_set=Order.objects.filter(order_number=order_number,user=request.user)
        for order in order_query_set:
            phy_queryset=order.physical_distribution_history_set.all().order_by('time')
            ser=physicalDistributionHistorySerializer(phy_queryset,many=True)
            if not ser.data:
                return APIResponse(statusCode=400,message=ser.errors,code=400)
            phy_info.append(ser.data)
        return APIResponse(statusCode=200,data=phy_info,code=200)




from django.conf import settings
from .models import Order
import hashlib
import requests
from datetime import datetime
from django.db import transaction


# class WeChatPay:
#     def __init__(self):
#         self.appid = settings.WECHATPAY['APPID']
#         self.mch_id = settings.WECHATPAY['MCHID']
#         self.key = settings.WECHATPAY['KEY']
#         self.notify_url = settings.WECHATPAY['NOTIFY_URL']
#
#     def create_order(self, order):
#         """创建微信支付预订单"""
#         params = {
#             'appid': self.appid,
#             'mch_id': self.mch_id,
#             'nonce_str': self.generate_nonce_str(),
#             'body': f'订单支付-{order.order_number}',
#             'out_trade_no': order.order_number,
#             'total_fee': int(order.actual_payment * 100),  # 转换为分
#             'spbill_create_ip': '127.0.0.1',
#             'notify_url': self.notify_url,
#             'trade_type': 'JSAPI',
#             'openid': order.user.wx_openid  # 假设用户模型有微信openid字段
#         }
#
#         # 生成签名并构造XML请求
#         params['sign'] = self.generate_sign(params)
#         xml_data = self.dict_to_xml(params)
#
#         # 调用微信统一下单接口
#         response = requests.post(
#             'https://api.mch.weixin.qq.com/pay/unifiedorder',
#             data=xml_data,
#             headers={'Content-Type': 'application/xml'}
#         )
#
#         # 解析返回结果
#         result = self.xml_to_dict(response.content)
#         if result.get('return_code') == 'SUCCESS' and result.get('result_code') == 'SUCCESS':
#             return {
#                 'prepay_id': result['prepay_id'],
#                 'nonce_str': result['nonce_str']
#             }
#         raise Exception(f"微信支付下单失败: {result.get('err_code_des')}")
#
#     # def process_notify(self, data):
#     #     """处理支付结果通知"""
#     #     # 验证签名
#     #     if not self.verify_sign(data):
#     #         raise Exception("签名验证失败")
#     #
#     #     with transaction.atomic():
#     #         order = Order.objects.select_for_update().get(
#     #             order_number=data['out_trade_no']
#     #         )
#     #         # 避免重复处理
#     #         if order.order_of_payment != 1:
#     #             return True
#     #
#     #         # 更新订单状态
#     #         order.order_of_payment = 2  # 待发货状态
#     #         order.transaction_id = data['transaction_id']
#     #         order.pay_time = datetime.strptime(data['time_end'], '%Y%m%d%H%M%S')
#     #         order.save()
#     #
#     #     return True
#
#     # 以下是工具方法（示例代码需要补充完整实现）
#     def generate_sign(self, params):
#         """生成微信支付签名"""
#         # 实现签名逻辑...
#         return
#
#     def verify_sign(self, params):
#         """验证签名"""
#         # 实现验证逻辑...
#
#     def dict_to_xml(self, params):
#         """字典转XML"""
#         # 实现转换逻辑...
#
#     def xml_to_dict(self, xml):
#         """XML转字典"""
#         # 实现转换逻辑...
#
#     @staticmethod
#     def generate_nonce_str(length=32):
#         """生成随机字符串"""
#         # 实现生成逻辑...


class WeChatPay(GenericViewSet):
    permission_classes = [IsAuthenticated]
    authentication_classes = [JSONWebTokenAuthentication]
    @action(detail=False, methods=['GET'])
    def get_pay_mini_info(self, request,*args,**kwargs):
        order_number=request.GET['order_number']
        order=Order.objects.filter(order_number=order_number,user=request.user)
        total_price=0
        for item in order:
            total_price+=Decimal(str(item.actual_payment)) + Decimal(str(item.freight))
        """创建微信支付预订单"""
        params = {
            'appid': settings.WECHATPAY['APPID'],
            'mch_id': settings.WECHATPAY['MCHID'],
            'nonce_str': self.generate_nonce_str(),
            'body': f'订单支付-{order_number}',
            'out_trade_no': order_number,
            'total_fee': int(total_price * 100),  # 转换为分
            'spbill_create_ip': '127.0.0.1',
            'notify_url': settings.WECHATPAY['NOTIFY_URL'],
            'trade_type': 'JSAPI',
            # 'openid': order.user.wx_openid  # 假设用户模型有微信openid字段
        }

        # 生成签名并构造XML请求
        params['sign'] = self.generate_sign(params)
        # xml_data = self.dict_to_xml(params)
        # 调用微信统一下单接口
        # response = requests.post(
        #     'https://api.mch.weixin.qq.com/pay/unifiedorder',
        #     data=xml_data,
        #     headers={'Content-Type': 'application/xml'}
        # )

        # 解析返回结果
        # result = self.xml_to_dict(response.content)
        # if result.get('return_code') == 'SUCCESS' and result.get('result_code') == 'SUCCESS':
        #     return {
        #         'prepay_id': result['prepay_id'],
        #         'nonce_str': result['nonce_str']
        #     }
        # raise Exception(f"微信支付下单失败: {result.get('err_code_des')}")
        return APIResponse(statusCode=200,data=params)
    # 以下是工具方法（示例代码需要补充完整实现）
        # 实现签名逻辑...
    def generate_sign(self, params):
        """生成微信支付签名"""
        # 过滤空值和sign字段，并按字段名ASCII码排序
        filtered = [(k, v) for k, v in params.items() if v not in (None, '') and k != 'sign']
        sorted_params = sorted(filtered, key=lambda x: x[0])

        # 拼接成URL键值对格式
        string_sign = '&'.join([f"{k}={v}" for k, v in sorted_params])

        # 添加商户密钥并生成MD5签名
        string_sign += f"&key={settings.WECHATPAY['KEY']}"
        md5 = hashlib.md5()
        md5.update(string_sign.encode('utf-8'))
        return md5.hexdigest().upper()

    def verify_sign(self, params):
        """验证签名"""
        # 获取原始签名并复制参数
        received_sign = params.get('sign', '')
        verify_params = params.copy()

        # 生成本地签名进行比较
        local_sign = self.generate_sign(verify_params)
        return received_sign == local_sign

    def dict_to_xml(self, params):
        """字典转XML"""
        xml = ["<xml>"]
        for key, value in params.items():
            if value is None:
                continue
            if isinstance(value, (int, float)):
                xml.append(f"<{key}>{value}</{key}>")
            else:
                xml.append(f"<{key}><![CDATA[{value}]]></{key}>")
        xml.append("</xml>")
        return "".join(xml)

    def xml_to_dict(self, xml):
        """XML转字典"""
        from xml.etree import ElementTree as ET
        try:
            root = ET.fromstring(xml)
            return {child.tag: child.text for child in root}
        except ET.ParseError as e:
            raise ValueError(f"XML解析失败: {str(e)}")

    @staticmethod
    def generate_nonce_str(length=32):
        """生成随机字符串"""
        import random
        import string
        chars = string.ascii_letters + string.digits
        return ''.join(random.choice(chars))